package simple; /**
 * @projectName study-note
 * @package PACKAGE_NAME
 * @className PACKAGE_NAME.LongestCommonPrefix
 */

/**
 * LongestCommonPrefix
 * @description 最长公共前缀
 * @author answer_wx
 * @date 2022/6/29 22:24
 * @version 1.0
 */
public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length < 1) {
            return "";
        } else if (strs.length == 1) {
            return strs[0];
        }
        int length = strs[0].length();
        for (int i = 1; i < strs.length; i++) {
            if (strs[i].length() < length) {
                length = strs[i].length();
            }
        }
        String prefix = "";
        for (int i = length; i > 0; i--) {
            int count = 0;
            int j = 0;
            prefix = strs[0].substring(0, i);
            while (j < strs.length) {
                if (!prefix.equals(strs[j].substring(0, i))) {
                    j++;
                    break;
                } else {
                    j++;
                    count++;
                }
            }
            if (strs.length == count) {
                return prefix;
            }
        }
        return "";
    }

    public static void main(String[] args) {
        String[] strs = {"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix(strs));
    }
}